//
//  ZFInTableViewController.m
//  TestPrj
//
//  Created by 朱铅峰 on 2019/12/24.
//  Copyright © 2019 Xing. All rights reserved.
//

#import "ZFInTableViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "ZFVideoListCell.h"
#import "ZFTableData.h"
#import <ZFPlayer/ZFPlayer.h>
#import <ZFPlayer/ZFAVPlayerManager.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import "ZFCustomControlView.h"

@interface ZFInTableViewController ()

proStrong NSMutableArray<ZFTableData *> *dataSource;
proStrong NSMutableArray *urls;

@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView; //自定义的控制视图 ZFCustomControlView
@property (nonatomic, strong) UIActivityIndicatorView *activity;

@property (nonatomic, copy) void(^listScrollViewScrollCallback)(UIScrollView *scrollView);//为了‘GKPageScrollView测试’应用该案例使用

@end

@implementation ZFInTableViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    @weakify(self)
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZFVideoListCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"ZFVideoListCell"];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    self.tableView.separatorColor = RGB(0.85, 0.85, 0.85);
    self.tableView.tableFooterView = [UIView new];
//    /// 停止的时候找出最合适的播放
//    self.tableView.zf_scrollViewDidStopScrollCallback = ^(NSIndexPath * _Nonnull indexPath) {
//        @strongify(self)
//        if (!self.player.playingIndexPath) {
//            [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
//        }
//    };
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header = header;
    MJRefreshFooter *footer = [MJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(doNothing)];
    self.tableView.mj_footer = footer;
    
    [self.view addSubview:self.activity];
    self.activity.center = self.view.center;
    
    /// AVPlayer作为内核
    ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
    
    /// player的tag值必须在cell里设置
    self.player = [ZFPlayerController playerWithScrollView:self.tableView playerManager:playerManager containerViewTag:[ZFVideoListCell videoContainerViewTag]];
    self.player.controlView = self.controlView;
    //self.player.WWANAutoPlay = YES;/// 移动网络依然自动播放
    self.player.playerDisapperaPercent = 1.0;/// 1.0是完全消失的时候
    self.player.playerApperaPercent = 0.0;/// 0.0是刚开始显示的时候
    self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
        @strongify(self)
        [self setNeedsStatusBarAppearanceUpdate];
        [UIViewController attemptRotationToDeviceOrientation];
        self.tableView.scrollsToTop = !isFullScreen;
    };
    self.player.playerDidToEnd = ^(id  _Nonnull asset) {
        @strongify(self)
        [self.controlView resetControlView];
        [self.player stopCurrentPlayingCell];
    };
    
    /// 以下设置滑出屏幕后不停止播放
    self.player.stopWhileNotVisible = NO;
    
    CGFloat margin = 20;
    CGFloat w = kScreenWidth/2;
    CGFloat h = w * 9/16;
    CGFloat x = kScreenWidth - w - margin;
    CGFloat y = kScreenHeight - h - margin;
    self.player.smallFloatView.frame = CGRectMake(x, y, w, h);
    
    [self requestData:NO];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.player.viewControllerDisappear = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    self.player.viewControllerDisappear = YES;
}

- (void)willMoveToParentViewController:(UIViewController *)parent {
    
    if (!parent) {
        self.tableView.delegate = nil;
        [self.player stopCurrentPlayingCell];
    }
}

/// 模拟获取数据的过程
- (void)requestData:(BOOL)isRandom {
    
    self.urls = @[].mutableCopy;
    [self.activity startAnimating];
    @weakify(self)
    /// 模拟网络请求
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        @strongify(self)
        
        [self.activity stopAnimating];
        [self.tableView.mj_header endRefreshing];
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        NSDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        self.dataSource = @[].mutableCopy;
        NSArray *videoList = [rootDict objectForKey:@"list"];
        if (isRandom) {
            NSMutableArray *MutVideoList = [NSMutableArray arrayWithArray:videoList];
            for (int i=0; i<MutVideoList.count; i++) {
                int pIndex = arc4random()%MutVideoList.count;
                if (i != pIndex) {
                    [MutVideoList exchangeObjectAtIndex:i withObjectAtIndex:pIndex];
                }
            }
            videoList = MutVideoList;
        }
        
        for (NSDictionary *dataDic in videoList) {
            ZFTableData *data = [[ZFTableData alloc] init];
            [data setValuesForKeysWithDictionary:dataDic];
            [self.dataSource addObject:data];
            NSString *URLString = [data.video_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            NSURL *url = [NSURL URLWithString:URLString];
            [self.urls addObject:url];
        }
        self.player.assetURLs = self.urls;
        
        [self.tableView reloadData];
        
//        /// 找到可播放的cell
//        [self.tableView zf_filterShouldPlayCellWhileScrolled:^(NSIndexPath *indexPath) {
//            @strongify(self)
//            [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
//        }];
    });
}

/// 获取新数据
- (void)loadNewData {
    
    [self.player stopCurrentPlayingCell];
    
    [self requestData:YES];
}

- (void)doNothing {}

#pragma mark - 懒加载

- (UIActivityIndicatorView *)activity {
    if (!_activity) {
        _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activity.hidesWhenStopped = YES;
    }
    return _activity;
}

- (ZFPlayerControlView *)controlView { //ZFCustomControlView
    if (!_controlView) {
        _controlView = [ZFPlayerControlView new];//ZFCustomControlView
    }
    return _controlView;
}
    
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSLog(@" ===== count: %d",(int)self.dataSource.count);
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZFVideoListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZFVideoListCell" forIndexPath:indexPath];
    ZFTableData *data = [_dataSource objectAtIndex:indexPath.row];
    [cell loadData:data];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewAutomaticDimension;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    /// 如果正在播放的index和当前点击的index不同，则停止当前播放的index
    if (self.player.playingIndexPath != indexPath) {
        [self.player stopCurrentPlayingCell];
    }
    /// 如果没有播放，则点击进详情页会自动播放
    if (!self.player.currentPlayerManager.isPlaying) {
        [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
    }
//    /// 到详情页
//    ZFPlayerDetailViewController *detailVC = [ZFPlayerDetailViewController new];
//    detailVC.player = self.player;
//    @weakify(self)
//    /// 详情页返回的回调
//    detailVC.detailVCPopCallback = ^{
//        @strongify(self)
//        [self.player addPlayerViewToCell];
//    };
//    /// 详情页点击播放的回调
//    detailVC.detailVCPlayCallback = ^{
//        @strongify(self)
//        [self zf_playTheVideoAtIndexPath:indexPath];
//    };
//    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - UIScrollViewDelegate  列表播放必须实现

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidEndDecelerating];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [scrollView zf_scrollViewDidEndDraggingWillDecelerate:decelerate];
}

- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewDidScrollToTop];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [scrollView zf_scrollViewDidScroll];
    
    //为了‘GKPageScrollView测试’应用该案例使用
    if (self.listScrollViewScrollCallback) {
        self.listScrollViewScrollCallback(scrollView);
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [scrollView zf_scrollViewWillBeginDragging];
}

#pragma mark - ZFTableViewCellDelegate

- (void)zf_playTheVideoAtIndexPath:(NSIndexPath *)indexPath {
    [self playTheVideoAtIndexPath:indexPath scrollToTop:NO];
}

#pragma mark - private method

/// play the video
- (void)playTheVideoAtIndexPath:(NSIndexPath *)indexPath scrollToTop:(BOOL)scrollToTop {
    
    [self.player playTheIndexPath:indexPath scrollToTop:scrollToTop];
    
    ZFTableData *data = [_dataSource objectAtIndex:indexPath.row];
    BOOL isVertical = data.video_width < data.video_height;
    
    [self.controlView showTitle:data.title coverURLString:data.thumbnail_url fullScreenMode:isVertical?ZFFullScreenModePortrait:ZFFullScreenModeLandscape];
    //[self.controlView showCoverViewWithUrl:data.thumbnail_url withImageMode:isVertical?UIViewContentModeScaleAspectFit:UIViewContentModeScaleToFill];
}

#pragma mark - 系统

- (BOOL)shouldAutorotate {
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen && self.player.orientationObserver.fullScreenMode == ZFFullScreenModeLandscape) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.player.isFullScreen) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    /// 如果只是支持iOS9+ 那直接return NO即可，这里为了适配iOS8
    return self.player.isStatusBarHidden;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

#pragma mark - GKPageListViewDelegate 实现GKPageListViewDelegate只是为了‘GKPageScrollView测试’这个案例的正常使用，与本例无关

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.tableView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    
    self.listScrollViewScrollCallback = callback;
}

@end
